package com.bamboocloud.ws;

import com.alibaba.fastjson.JSON;
import com.banboocloud.Codec.BamboocloudFacade;
import com.banboocloud.Codec.Sm3Signature;
import com.banboocloud.Codec.Sm4Cipher;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/***
 * SchemaService  第三方目标系统中“账号”等对象全部属性
 * */
public class EncryptTest {
    public static void main(String[] args) {
        //sm3签名
        Map<String,Object> map=new HashMap<>();
        map.put("bimRequestId","9e928d12ec8a4c1bb75283b8df71308d");
        map.put("bimRemotePwd","/XJnx?Uw<g2-u#4C");
        map.put("bimRemoteUser","xkepsadmin");

        Sm3Signature signature = new Sm3Signature();
        String signatureStr = signature.signature(getStr(map));

        System.out.println("RESULT:" + signature.verify(signatureStr,JSON.toJSONString(map)));

        System.out.println("signatureStr:" + signatureStr);
        //sm4加解密
        String key = "SIDAKD87F7W7LNEQ";

        Sm4Cipher sm4Cipher = new Sm4Cipher();
        map.put("signature",signatureStr);
        String source = JSON.toJSONString(map);
        String target = sm4Cipher.encrypt(source, key);

        //输出密文
        System.out.println("target:" + target);
    }

    public static String getStr(Map<String, Object> reqmap) {
        Map<String, Object> verifymap = new TreeMap<String, Object>();
        StringBuffer sb = new StringBuffer();
        Iterator<String> it = reqmap.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            verifymap.put(key, reqmap.get(key));
        }
        Iterator<String> ittree = verifymap.keySet().iterator();
        while (ittree.hasNext()) {
            String key = (String) ittree.next();
            if (!"signature".equals(key)) {
                sb.append(key).append("=").append(verifymap.get(key)).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);

        return sb.toString();

    }
}
